package com.icart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icart.comm.AjaxRspResult;
import com.icart.context.HttpUserContext;
import com.icart.context.SaleUserContext;
import com.icart.context.provider.UserContextProvider;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.entities.*;
import com.icart.repositories.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;


@Controller
@RequestMapping("/sale")
public class SaleOrderController {

    @Autowired
    HttpSession session;
    @Autowired
    private RestTemplate template;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private BiUserRepository biUserRepository;
    @Autowired
    private BiStaffRepository biStaffRepository;
    @Autowired
    private CustcarRepository custcarRepository;
    @Autowired
    private MksaleinfoRepository mksaleinfoRepository;
    @Autowired
    private MksalepicRepository mksalepicRepository;
    @Autowired
    private MkfwcodeRepository mkfwcodeRepository;
    @Autowired
    private WoinfoRepository woinfoRepository;

    /*获取session*/
    public SaleUserContext getsession(){
        ContextStorage storage=new SessionContextStorageImpl(request);
        SaleUserContext saleUserContext=storage.getsaleUserContext("saleUser");
        return saleUserContext;
    }

    /*获取微信个人的openid*/
    @RequestMapping("/index")
    public String getOpenId() {
        /* 师兄接口的token*/
        WxUtilController wxUtilController=new WxUtilController();
        String result=wxUtilController.getToken2(template,request);
        String requestUrl = "http://api.wechat.ikartek.com/wechat/oauth?name=Name&redirectUrl=RedirectUrl&token=Token";
        requestUrl = requestUrl.replace("Name","gh_3981ce9836d0");
        requestUrl = requestUrl.replace("RedirectUrl","http://testwx.ikartek.com/sale/login");
        requestUrl = requestUrl.replace("Token",result);
        System.out.println("Token="+result);
        System.out.println("requestUrl="+requestUrl);
        return "redirect:"+requestUrl;
    }
    /*登录页面*/
    @RequestMapping("/login")
    public String login(Model model) {
        String openid=request.getParameter("openid");
        System.out.println("openid="+openid);
        request.getSession().setAttribute("openid",openid);
        BiUserEntity biUserEntity=biUserRepository.loginfindopenid(openid);
        if(biUserEntity!=null){
        //设置在session里面
            BiChnstaffEntity biChnstaffEntity=biStaffRepository.findchnid(biUserEntity.getStaffid());
            SaleUserContext saleUserContext= UserContextProvider.createsale(biUserEntity.getStaffid(),biUserEntity.getUsername(),biChnstaffEntity.getChnid());
            ContextStorage storage=new SessionContextStorageImpl(request);
            storage.saveSale("saleUser",saleUserContext);
            return "redirect:/sale/order";
        }else {
            return "sale/login";
        }
    }

    /*微信服务器下载图片转base64*/
    @RequestMapping("/uploadpic")
    @ResponseBody
    public String uploadpic(@RequestParam(name = "mediaId",required = false) String mediaId,Model model){
        String base64=HomeController.getPic2(mediaId,template,request);
        System.out.println(base64);
        return base64;
    }

    /*退出登录*/
    @RequestMapping("/exit")
    public String exit(Model model){
        ContextStorage storage=new SessionContextStorageImpl(request);
        storage.clear("saleUser");
        return "sale/login";
    }

    /*加密算法*/
    public String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*点击登录按钮*/
    @RequestMapping("/logincheck")
    @ResponseBody
    public String logincheck(@RequestParam(name = "username",required = false) String username,
                             @RequestParam(name = "pwd",required = false) String pwd,Model model){
        String isflag="false";
        //加密算法
        String password=MD5(pwd);

       BiUserEntity biUserEntity=biUserRepository.login(username,password);
        if(biUserEntity!=null){
            isflag="true";
            /*设置在session里面*/
            BiChnstaffEntity biChnstaffEntity=biStaffRepository.findchnid(biUserEntity.getStaffid());
            SaleUserContext saleUserContext= UserContextProvider.createsale(biUserEntity.getStaffid(),biUserEntity.getUsername(),biChnstaffEntity.getChnid());
            ContextStorage storage=new SessionContextStorageImpl(request);
            storage.saveSale("saleUser",saleUserContext);
        }
        return isflag;
    }

    /*保存待评论订单详情*/
    @RequestMapping("/delsalepic")
    @ResponseBody
    public String delsalepic(Model model) {
        Long picid=Long.parseLong(request.getParameter("picid"));
        mksalepicRepository.deletepic(picid);
        return "success";
    }

    /*个人中心*/
    @RequestMapping("/saleperson")
    public String saleperson(Model model){
        List list=biUserRepository.createNativeQuery("select picurl from bi_chnpic where chnid="+getsession().getChnid());
        model.addAttribute("picurl",list.get(0));
        model.addAttribute("username",getsession().getUsername());
        model.addAttribute("staffid",getsession().getStaffid());

        String sql="select IFNULL(sum((select d.reward from mk_salereward d where d.servitemid=o.servitem and d.chnid=o.chnid and d.status=1)),0)allsum" +
                " from mk_saleinfo o where DATE_FORMAT(o.completetime,'%Y%m')=DATE_FORMAT( CURDATE(),'%Y%m') and o.completetime is not null and o.chnid="+getsession().getChnid();/*查出每个月的总数*/
        List list1=biUserRepository.createNativeQuery(sql);
        model.addAttribute("everyMoth",list1.get(0));/*查出每个月的总数*/

        List list3=biUserRepository.createNativeQuery("select wxid from bi_user where staffid="+getsession().getStaffid());
        model.addAttribute("wxintype",list3.get(0));

        return "sale/personhome";
    }

    /*修改微信绑定*/
    @RequestMapping("/saveUserwxid")
    @ResponseBody
    public String saveUserwxid(@RequestParam(name = "wxid",required = false) int wxidtype,
                               @RequestParam(name = "staffid",required = false) Long staffid,Model model) {
        System.out.println("wxid22="+wxidtype);
        System.out.println("staffid="+staffid);
        if(wxidtype==0){
            //解绑
            biUserRepository.updateUserwxid(null,staffid);
        }else {
            biUserRepository.updateUserwxid(request.getSession().getAttribute("openid").toString(),staffid);
        }
        return "success";
    }

    /*我的业绩*/
    @RequestMapping("/myPerformance")
    public String myPerformance(@RequestParam(name = "type",required = false) String type,
                                @RequestParam(name = "choocetime",required = false) String choocetime,Model model){
        Long staffid=getsession().getStaffid();
        String sql="select date_format(o.completetime, '%Y-%m')time," +
                "IFNULL(sum((select d.reward from mk_salereward d where d.servitemid=o.servitem and d.chnid=o.chnid and d.status=1)),0)allsum," +
                "IFNULL(sum((select d.reward from mk_salereward d where d.servitemid=o.servitem and d.chnid=o.chnid and d.status=1 and o.stat!=2)),0)notgetsum," +
                "IFNULL(sum((select d.reward from mk_salereward d where d.servitemid=o.servitem and d.chnid=o.chnid and d.status=1 and o.stat=2)),0)getsum " +
                "from mk_saleinfo o where o.completetime is not null and o.chnid="+getsession().getChnid()+" and o.staffid="+staffid;/*查出每个月的总数*/
        String sql2="select date_format(o.completetime,'%Y-%m')time,o.completetime,o.carno," +
                "(select m.dictname from sa_db_dictitem m where m.groupid='WO_SALETYPE' and m.dictid=o.stat)type," +
                "(select d.reward from mk_salereward d where d.servitemid=o.servitem and d.chnid=o.chnid)reward," +
                "(select m.servitemname from bi_servitem m where m.servitemid=o.servitem)servitemname" +
                " from mk_saleinfo o where o.completetime is not null and o.chnid="+getsession().getChnid()+" and o.staffid="+staffid;;/*查出每个月的明细*/
        if(type!=null){
            switch (type){
                case "1":sql2+=" and o.stat=2 ";String sst1="已结算";model.addAttribute("saletype",sst1);break;
                case "2":sql2+=" and o.stat!=2 ";String sst="未结算";model.addAttribute("saletype",sst);break;
            }
        }
        if(choocetime!=null){
            switch (choocetime){
                case "0":sql2+=" and o.completetime = to_days(now())";sql+=" and o.completetime = to_days(now())";String sst0="本日";model.addAttribute("choocetime",sst0);break;
                case "1":sql2+=" and DATE_FORMAT(o.completetime,'%Y%m')=DATE_FORMAT( CURDATE(),'%Y%m')";sql+=" and DATE_FORMAT(o.completetime,'%Y%m')=DATE_FORMAT( CURDATE(),'%Y%m')";String sst1="本月";model.addAttribute("choocetime",sst1);break;
                case "2":sql2+=" and o.completetime>= DATE_SUB( CURRENT_DATE(),INTERVAL 3 MONTH)";sql+=" and o.completetime>= DATE_SUB( CURRENT_DATE(),INTERVAL 3 MONTH)";String sst2="近三个月";model.addAttribute("choocetime",sst2);break;
            }
        }
        sql+="  group by date_format(o.completetime, '%Y-%m') order by o.completetime";
        List list1=biUserRepository.createNativeQuery(sql);
        model.addAttribute("everyMoth",list1);/*查出每个月的总数*/

        List list2=biUserRepository.createNativeQuery(sql2);
        model.addAttribute("salelist",list2);/*查出每个月的明细*/


        return "sale/myPerformance";
    }
    /*订单首页*/
    @RequestMapping("/order")
    public String order(Model model) {
        Long chnid=getsession().getChnid();
        Long staffid=getsession().getStaffid();
        String sql="select mk.*,(select servitemname from bi_servitem where servitemid=mk.servitem)servitemname from mk_saleinfo mk where mk.stat=-2 and mk.chnid="+chnid+" and mk.staffid="+staffid+" order by mk.createtime desc";
        List sale=mksaleinfoRepository.createNativeQuery(sql);
        model.addAttribute("order",sale);
        String sql1="select mk.*,(select servitemname from bi_servitem where servitemid=mk.servitem)servitemname from mk_saleinfo mk where mk.stat in(-1,0) and mk.chnid="+chnid+" and mk.staffid="+staffid+" order by mk.stat,mk.createtime desc";
        List sale1=mksaleinfoRepository.createNativeQuery(sql1);
        model.addAttribute("order1",sale1);
//        String str= "44444444";
//        byte[] b = Base64.encodeBase64(str.getBytes(), true);
//        String stra=new String(b);
//        System.out.println(stra);
        return "sale/order";

    }

    /*加载服务项目*/
    @RequestMapping("/loadserv")
    @ResponseBody
    public AjaxRspResult loadserv(Model model) {
        Long chnid=getsession().getChnid();
        String sql="select b.servitemid as value,b.servitemname as title from bi_servitem b,mk_saleReward m where m.servitemid=b.servitemid and m.chnid="+chnid;
        List list=mksaleinfoRepository.createNativeQuery(sql);
        AjaxRspResult arr=new AjaxRspResult();
        arr.setResult(list);
        return arr;
    }

    @RequestMapping("/create")
    public String addorder(Model model) {
        //查出车牌省份
        String sql2="select dictname from sa_db_dictitem where groupid='BI_CARNOHEAD'";
        List list2=mksaleinfoRepository.createNativeQuery(sql2);
        model.addAttribute("province",list2);
        if(request.getParameter("cartype")!=null) {
            String cartype = request.getParameter("cartype");
            List custcar = mksaleinfoRepository.createNativeQuery("select bc.cartypeid,(select brandlogo from bi_carbrand where brandid=bc.brandid)brandlogo," +
                    "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                    "bc.carvol,bc.caryear from bi_cardef bc where cartypeid='" + cartype + "'");
            model.addAttribute("custcar",custcar.get(0));
        }
         /*获取微信的token*/
        String url="http://pay.wechat.ikartek.com/jssdk/api.php?url=http://testwx.ikartek.com/sale/create&token=";
        HomeController.gettoken2(model,template,url,request);
//        String str= "123366666666333";
//        byte[] b = Base64.encodeBase64(str.getBytes(), true);
//        String stra=new String(b);
//        System.out.println(stra);
//        byte[] b2 = Base64.decodeBase64(stra.getBytes());
//        System.out.println(new String(b2));
        return "sale/create";
    }

    @RequestMapping("/update")
    public String updateorder(Model model) {
        //查出车牌省份
        String sql2="select dictname from sa_db_dictitem where groupid='BI_CARNOHEAD'";
        List list2=mksaleinfoRepository.createNativeQuery(sql2);
        model.addAttribute("province",list2);
        String oid = request.getParameter("oid");
        MkSaleinfoEntity mk=mksaleinfoRepository.saleinfo(oid);
        if(mk.getCartype()!=null) {
            String cartype = mk.getCartype();
            List custcar = mksaleinfoRepository.createNativeQuery("select bc.cartypeid,(select brandlogo from bi_carbrand where brandid=bc.brandid)brandlogo," +
                    "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                    "bc.carvol,bc.caryear from bi_cardef bc where cartypeid='" + cartype + "'");
            model.addAttribute("custcar",custcar.get(0));
        }
        List serv=mksaleinfoRepository.createNativeQuery("select servitemname from bi_servitem where servitemid="+mk.getServitem());
        String sqlpic1="select * from mk_salepic where oid='" + oid + "' and pickind=1";
        List pic1=mksaleinfoRepository.createNativeQuery(sqlpic1);
        String sqlpic2="select * from mk_salepic where oid='" + oid + "' and pickind=2";
        List pic2=mksaleinfoRepository.createNativeQuery(sqlpic2);
        String sqlpic3="select * from mk_salepic where oid='" + oid + "' and pickind=3";
        List pic3=mksaleinfoRepository.createNativeQuery(sqlpic3);
        String sqlpic4="select * from mk_salepic where oid='" + oid + "' and pickind=4";
        List pic4=mksaleinfoRepository.createNativeQuery(sqlpic4);
        String sqlpic5="select * from mk_salepic where oid='" + oid + "' and pickind=5";
        List pic5=mksaleinfoRepository.createNativeQuery(sqlpic5);
        String sqlpic6="select * from mk_salepic where oid='" + oid + "' and pickind=6";
        List pic6=mksaleinfoRepository.createNativeQuery(sqlpic6);
        String sqlpic7="select * from mk_salepic where oid='" + oid + "' and pickind=7";
        List pic7=mksaleinfoRepository.createNativeQuery(sqlpic7);
        String sqlpic8="select * from mk_salepic where oid='" + oid + "' and pickind=8";
        List pic8=mksaleinfoRepository.createNativeQuery(sqlpic8);
        String sqlpic9="select * from mk_salepic where oid='" + oid + "' and pickind=9";
        List pic9=mksaleinfoRepository.createNativeQuery(sqlpic9);
        List<MkFwcodeEntity> fwcodes=mkfwcodeRepository.fwcode(oid);
        for(MkFwcodeEntity m:fwcodes){
            byte[] b2 = Base64.decodeBase64(m.getFwcode().getBytes());
            String fwcode=new String(b2);
            m.setFwcode(fwcode);
        }
        model.addAttribute("pic1",pic1);
        model.addAttribute("pic2",pic2);
        model.addAttribute("pic3",pic3);
        model.addAttribute("pic4",pic4);
        model.addAttribute("pic5",pic5);
        model.addAttribute("pic6",pic6);
        model.addAttribute("pic7",pic7);
        model.addAttribute("pic8",pic8);
        model.addAttribute("pic9",pic9);
        model.addAttribute("mk",mk);
        model.addAttribute("serv",serv.get(0));
        model.addAttribute("fwcodes",fwcodes);
        return "sale/update";
    }

//    private static List list1=new ArrayList();
//    private static List list2=new ArrayList();
//    private static List list3=new ArrayList();
//    private static List list4=new ArrayList();
//    private static List list5=new ArrayList();
//    /*保存*/
//    @RequestMapping("/savelist")
//    @ResponseBody
//    public void savelist(Model model) {
//        String kind=request.getParameter("kind");
//        String url=request.getParameter("url");
//        if(kind.equals("1")){
//            list1.add(url);
//        }
//        if(kind.equals("2")){
//            list2.add(url);
//        }
//        if(kind.equals("3")){
//            list3.add(url);
//        }
//        if(kind.equals("4")){
//            list4.add(url);
//        }
//        if(kind.equals("5")){
//            list5.add(url);
//        }
//    }

    /*保存*/
    @RequestMapping("/savesale")
    @ResponseBody
    public String savesale(Model model) {
        Long chnid=getsession().getChnid();
        Long staffid=getsession().getStaffid();
        String info=request.getParameter("info");
        JSONObject jsonObject= JSON.parseObject(info);
        System.out.println(jsonObject);
        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creattime=format.format(dates);//获取当前系统时间

        String oid=nextId();//工单号
        String carno=jsonObject.getString("carno");
        String cartype=jsonObject.getString("cartype");
        String textarea=jsonObject.getString("textarea");
        String waternum=jsonObject.getString("waternum");
        Long serv=Long.parseLong(jsonObject.getString("serv"));
        JSONArray list1=jsonObject.getJSONArray("list1");//图片路径列表
        JSONArray list2=jsonObject.getJSONArray("list2");//图片路径列表
        JSONArray list3=jsonObject.getJSONArray("list3");//图片路径列表
        JSONArray list4=jsonObject.getJSONArray("list4");//视频路径列表
        JSONArray list5=jsonObject.getJSONArray("list5");//视频路径列表
        JSONArray list6=jsonObject.getJSONArray("list6");//视频路径列表
        JSONArray list7=jsonObject.getJSONArray("list7");//视频路径列表
        JSONArray list8=jsonObject.getJSONArray("list8");//视频路径列表
        JSONArray list9=jsonObject.getJSONArray("list9");//视频路径列表
        JSONArray listfwcode=jsonObject.getJSONArray("listfwcode");//视频路径列表
        mksaleinfoRepository.insert(oid,chnid,null,serv,null,carno,cartype,creattime,textarea,-2,staffid,waternum);
        for(int i=0;i<list1.size();i++){
            mksalepicRepository.insert(oid,chnid,list1.get(i).toString(),1);
        }
        for(int i=0;i<list2.size();i++){
            mksalepicRepository.insert(oid,chnid,list2.get(i).toString(),2);
        }
        for(int i=0;i<list3.size();i++){
            mksalepicRepository.insert(oid,chnid,list3.get(i).toString(),3);
        }
        for(int i=0;i<list4.size();i++){
            mksalepicRepository.insert(oid,chnid,list4.get(i).toString(),4);
        }
        for(int i=0;i<list5.size();i++){
            mksalepicRepository.insert(oid,chnid,list5.get(i).toString(),5);
        }
        for(int i=0;i<list6.size();i++){
            mksalepicRepository.insert(oid,chnid,list6.get(i).toString(),6);
        }
        for(int i=0;i<list7.size();i++){
            mksalepicRepository.insert(oid,chnid,list7.get(i).toString(),7);
        }
        for(int i=0;i<list8.size();i++){
            mksalepicRepository.insert(oid,chnid,list8.get(i).toString(),8);
        }
        for(int i=0;i<list9.size();i++){
            mksalepicRepository.insert(oid,chnid,list9.get(i).toString(),9);
        }
        for(int i=0;i<listfwcode.size();i++){
            byte[] b = Base64.encodeBase64(listfwcode.get(i).toString().getBytes(), true);
            mkfwcodeRepository.insert(oid,new String(b));
        }
        return "success";
    }

    /*更新*/
    @RequestMapping("/updatesale")
    @ResponseBody
    public String updatesale(Model model) {
        Long chnid=getsession().getChnid();
        String info=request.getParameter("info");
        JSONObject jsonObject= JSON.parseObject(info);
        System.out.println(jsonObject);

        String oid=jsonObject.getString("oid");
        String carno=jsonObject.getString("carno");
        String textarea=jsonObject.getString("textarea");
        String waternum=jsonObject.getString("waternum");
        Long serv=Long.parseLong(jsonObject.getString("serv"));
        JSONArray list1=jsonObject.getJSONArray("list1");//图片路径列表
        JSONArray list2=jsonObject.getJSONArray("list2");//图片路径列表
        JSONArray list3=jsonObject.getJSONArray("list3");//图片路径列表
        JSONArray list4=jsonObject.getJSONArray("list4");//视频路径列表
        JSONArray list5=jsonObject.getJSONArray("list5");//视频路径列表
        JSONArray list6=jsonObject.getJSONArray("list6");//视频路径列表
        JSONArray list7=jsonObject.getJSONArray("list7");//视频路径列表
        JSONArray list8=jsonObject.getJSONArray("list8");//视频路径列表
        JSONArray list9=jsonObject.getJSONArray("list9");//视频路径列表
        mksaleinfoRepository.update(carno,textarea,serv,waternum,oid);
        for(int i=0;i<list1.size();i++){
            mksalepicRepository.insert(oid,chnid,list1.get(i).toString(),1);
        }
        for(int i=0;i<list2.size();i++){
            mksalepicRepository.insert(oid,chnid,list2.get(i).toString(),2);
        }
        for(int i=0;i<list3.size();i++){
            mksalepicRepository.insert(oid,chnid,list3.get(i).toString(),3);
        }
        for(int i=0;i<list4.size();i++){
            mksalepicRepository.insert(oid,chnid,list4.get(i).toString(),4);
        }
        for(int i=0;i<list5.size();i++){
            mksalepicRepository.insert(oid,chnid,list5.get(i).toString(),5);
        }
        for(int i=0;i<list6.size();i++){
            mksalepicRepository.insert(oid,chnid,list6.get(i).toString(),6);
        }
        for(int i=0;i<list7.size();i++){
            mksalepicRepository.insert(oid,chnid,list7.get(i).toString(),7);
        }
        for(int i=0;i<list8.size();i++){
            mksalepicRepository.insert(oid,chnid,list8.get(i).toString(),8);
        }
        for(int i=0;i<list9.size();i++){
            mksalepicRepository.insert(oid,chnid,list9.get(i).toString(),9);
        }
        return "success";
    }

    /*提交*/
    @RequestMapping("/updatestat")
    @ResponseBody
    public String updatestat(Model model) {
        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creattime=format.format(dates);//获取当前系统时间
        String oid=request.getParameter("oid");
        mksaleinfoRepository.updatestat(creattime,oid);
        return "success";
    }

    @RequestMapping("/checkfw")
    @ResponseBody
    public String checkfw(Model model) {
        String fwcode=request.getParameter("fwcode");
        byte[] b = Base64.encodeBase64(fwcode.getBytes(), true);
        String fw=new String(b);
        String fwc="'"+fw+"'";
        String fwcc=fwc.replaceAll("\r|\n", "");
        List list=mksaleinfoRepository.createNativeQuery("select * from bi_forglab where labid="+fwcc+" and stat=0");
        if(list.size()==0){
            return "fail";
        } else {
            return "success";
        }
    }

    private static final String HEAD = "SD";

    /** 序列在id中占的位数 */
    private static final long sequenceBits = 26L;

    /** 生成序列的掩码，这里为67108863 (0b11111111111111111111111111=0x3ffffff=67108863) */
    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 毫秒内序列(0~67108863) */
    private static long sequence = -1L;

    /** 上次生成ID的时间截 */
    private static long lastTimestamp = -1L;

    public synchronized String nextId() {
        long timestamp = timeGen();

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        if(sequence == -1){
            //初始化序列号
            initSequence(dateFormat.format(timestamp));
            lastTimestamp = timestamp;
        }

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一天生成的，则进行当天内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //异常
                throw new RuntimeException(String.format("工单序列溢出"));
            }
        }
        //时间戳改变，当天内序列重置
        else {
            sequence = 1L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //拼接返回workId
        DecimalFormat df = new DecimalFormat("00000000");
        return HEAD + dateFormat.format(new Date(timestamp)) + df.format(sequence);
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当天零点零分零秒(毫秒)
     */
    protected long timeGen() {
        //今天零点零分零秒的毫秒数
        return System.currentTimeMillis()/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();
    }

    /**
     * 初始化当前序列
     */
    protected void initSequence(String day) {
        String curoid = mksaleinfoRepository.findmaxid( HEAD + day + "%");
        if(curoid == null){
            sequence = 0L;
        } else {
            sequence = Long.valueOf(curoid.substring(10));
        }
    }
}